package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {


    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 获取当前用户的地址簿
     */
    @Override
    public List<AddressBook> getAddressBookList() {
        Long currentId = BaseContext.getCurrentId();
        log.info("获取当前用户的地址簿:{}", currentId);
        return addressBookMapper.getAddressBookListByUserId(currentId);
    }


    /**
     * 新增地址
     *
     * @param addressBook
     */
    @Override
    public void addAddress(AddressBook addressBook) {
        Long currentId = BaseContext.getCurrentId();
        List<AddressBook> addressBooks = addressBookMapper.getAddressBookListByUserId(currentId);
        // 如果当前用户的地址簿中还没有地址信息，则新增的第一条地址信息为默认地址信息
        if (addressBook.getIsDefault() == null && (addressBooks == null || addressBooks.isEmpty())) {
            addressBook.setIsDefault(1);
        } else if (addressBook.getIsDefault() == null) {
            // 当当前用户的地址簿不是空且当前请求中前端为指定isDeafult的值，我们给一个默认值0
            addressBook.setIsDefault(0);
        }
        // 设置userID为当前登录用户的id
        addressBook.setUserId(currentId);
        addressBookMapper.insertAddress(addressBook);
    }


    @Override
    public AddressBook getAddresById(Integer id) {
        return addressBookMapper.getAddresById(id);

    }


    /**
     * 设置默认地址
     * @param addressBook
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefaultAddress(AddressBook addressBook) {

        AddressBook afterDefaultAddress =
                addressBookMapper.getUserDefaultAddress (BaseContext.getCurrentId());

        // 修改旧的默认地址
        afterDefaultAddress.setIsDefault(0);
        addressBookMapper.updateAddress(afterDefaultAddress);

        // 设置新的默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.updateAddress(addressBook);
    }


    /**
     * 查询默认地址
     * @return
     */
    @Override
    public AddressBook getDefaultAddress() {
        return addressBookMapper.getUserDefaultAddress(BaseContext.getCurrentId());
    }


    /**
     * 根据id修改地址
     * @param addressBook
     */
    @Override
    public void updateAddress(AddressBook addressBook) {
        addressBookMapper.updateAddress(addressBook);
    }


    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void deleteAddress(Long id) {
        addressBookMapper.deleteAddressById(id);
    }
}
